<?php

namespace Home\Controller;

use Common\Model\BbsModel;
use Common\Model\DocModel;
use Common\Model\TieModel;
use Common\Model\UserModel;
use Think\Controller;
use Think\Log;

class TaskController extends Controller
{

    /**
     * 从 redis 中更新缓存数据到数据库
     */
    public function syn()
    {
        set_time_limit(0);
        $file = RUNTIME_PATH.'Logs/syn_'.date('Y_m_d').'.txt';
        $redis = S(C('CACHE_REDIS_CONF'));
        // 更新帖子计数数据
        $tieKeys = $redis->keys('tmp:tie:*');
        foreach ($tieKeys as $tieKey) {
            $id = substr($tieKey, 8);
            $arr = $redis->get($tieKey);
            $data = [];
            foreach ($arr as $k => $v) {
                if ($v != 0) {
                    $data[$k] = ['exp', '`' . $k . '` + ' . $v];
                }
            }
            if ($data) {
                if (!TieModel::update($id, $data)) {
                    error_log('['.date('Y-m-d H:i:s').']： '.$tieKey." => ".json_encode($data)."\n", 3, $file);
                }
            }
            $redis->rm($tieKey);
            sleep(0.2);
        }
        sleep(2);
        // 更新社区计数数据
        $bbsKeys = $redis->keys('tmp:bbs:*');
        foreach ($bbsKeys as $bbsKey) {
            $id = substr($bbsKey, 8);
            $arr = $redis->get($bbsKey);
            $data = [];
            foreach ($arr as $k => $v) {
                if ($v != 0) {
                    $data[$k] = ['exp', '`' . $k . '` + ' . $v];
                }
            }
            if ($data) {
                if (!BbsModel::update($id, $data)) {
                    error_log('['.date('Y-m-d H:i:s').']： '.$bbsKey." => ".json_encode($data)."\n", 3, $file);
                }
            }
            $redis->rm($bbsKey);
            sleep(0.2);
        }
        sleep(2);
        // 更新文档计数数据
        $docKeys = $redis->keys('tmp:doc:*');
        foreach ($docKeys as $docKey) {
            $id = substr($docKey, 8);
            $arr = $redis->get($docKey);
            $data = [];
            foreach ($arr as $k => $v) {
                if ($v != 0) {
                    $data[$k] = ['exp', '`' . $k . '` + ' . $v];
                }
            }
            if ($data) {
                if (!DocModel::update($id, $data)) {
                    error_log('['.date('Y-m-d H:i:s').']： '.$docKey." => ".json_encode($data)."\n", 3, $file);
                }
            }
            $redis->rm($docKey);
            sleep(0.2);
        }
        sleep(2);
        // 更新用户计数数据
        $userKeys = $redis->keys('tmp:user:*');
        foreach ($userKeys as $userKey) {
            $id = substr($userKey, 9);
            $arr = $redis->get($userKey);
            $data = [];
            foreach ($arr as $k => $v) {
                if ($v != 0) {
                    $data[$k] = ['exp', '`' . $k . '` + ' . $v];
                }
            }
            if ($data) {
                if (!UserModel::update($id, $data)) {
                    error_log('['.date('Y-m-d H:i:s').']： '.$userKey." => ".json_encode($data)."\n", 3, $file);
                }
            }
            $redis->rm($userKey);
            sleep(0.2);
        }
    }

    /**
     * 统计脚本
     */
    public function statistics()
    {
        // 每天、每周、每月、每季度、每年 统计一次
        // 新增用户、社区、文档（公有/私有/总计）、文章、话题、回复、建议
        $last = M('Statistics')->order('id desc')->find();
        $yestoday = date('Y-m-d', time() - 3600 * 24);
        if (substr($last['time'], 0, 10) == $yestoday) {
            return false;
        }
        $startTime = strtotime($yestoday . ' 00:00:00');
        $endTime = strtotime($yestoday . ' 23:59:59');
        $where = '`create` >= ' . $startTime . ' and `create` <= ' . $endTime;

        $users = M('User')->where($where)->count();
        $bbss = M('Bbs')->where($where)->count();
        $docs = M('Doc')->where($where)->count();
        $privatedocs = M('Doc')->where($where . ' and bid = 0')->count();
        $publicdocs = M('Doc')->where($where . ' and bid <> 0')->count();
        $articles = M('Article')->where($where)->count();
        $ties = M('Tie')->where($where)->count();
        $answers = M('Ans')->where($where)->count();
        $suggests = M('Suggest')->where($where)->count();
        $data = [
            'users' => $users,
            'bbss' => $bbss,
            'docs' => $docs,
            'privatedocs' => $privatedocs,
            'publicdocs' => $publicdocs,
            'articles' => $articles,
            'ties' => $ties,
            'answers' => $answers,
            'suggests' => $suggests,
            'time' => $yestoday . ' 23:59:59',
            'type' => 1
        ];
        if (M('Statistics')->add($data)) {
            // send_email
        }
        // 周一
        if (date('w') == 1) {
            $startTime = date('Y-m-d', time() - 3600 * 24 * 7) . ' 00:00:00';
            $this->statisticByTime($startTime, 2);
        }
        // 1 号
        if (date('d') == '01') {
            $startTime = date('Y-m', time() - 3600 * 24 * 7) . '-01 00:00:00';
            $this->statisticByTime($startTime, 3);
        }
        $md = date('md');
        if ($md == '0401') {
            $startTime = date('Y') . '-01-01 00:00:00';
            $this->statisticByTime($startTime, 4);
        } else if ($md == '0701') {
            $startTime = date('Y') . '-04-01 00:00:00';
            $this->statisticByTime($startTime, 4);
        } else if ($md == '1001') {
            $startTime = date('Y') . '-07-01 00:00:00';
            $this->statisticByTime($startTime, 4);
        } else if ($md == '0101') {
            $prevYear = (int)date('Y') - 1;
            $startTime = $prevYear . '-10-01 00:00:00';
            $this->statisticByTime($startTime, 4);
            $startTime2 = $prevYear . '-01-01 00:00:00';
            $this->statisticByTime($startTime2, 5);
        }
        return true;
    }

    /**
     * @param $startTime
     * @param int $type
     * @return bool
     */
    private function statisticByTime($startTime, $type = 1)
    {
        $endTime = date('Y-m-d', time() - 3600 * 24) . ' 23:59:59';
        $where = 'time >= "' . $startTime . '" and time <= "' . $endTime . '"';
        $field = 'sum(users) as users,sum(bbss) as bbss,sum(docs) as docs,sum(privatedocs) as privatedocs,sum(publicdocs) as publicdocs,sum(articles) as articles,sum(ties) as ties,sum(answers) as answers,sum(suggests) as suggests';
        $data = M('Statistics')->where($where)->field($field)->select();
        $data[0]['time'] = date('Y-m-d', time() - 3600 * 24) . ' 23:59:59';
        $data[0]['type'] = $type;
        if (M('Statistics')->add($data[0])) {
            return true;
        }
        return false;
    }

    /**
     * 测试用例
     */
    public function test()
    {
        $file = RUNTIME_PATH.'Logs/syn_'.date('Y_m_d').'.txt';
        error_log('['.date('Y-m-d H:i:s')."]： 厉害呀我的哥"."\n", 3, $file);
    }

}